const { Service } = require('egg')
const cheerio = require('cheerio')
const { tableToList } = require('../utils/tools')

module.exports = class ExamService extends Service {
  /**
   * * 考试安排
   * @param {String} term 学期
   * @return {Array} *
   */
  async table(term) {
    const Cookie = this.ctx.state.Cookie
    const { sid } = this.ctx.data
    try {
      /* 在教务主页中获取成绩查询的链接 */
      const mainUrl = `${this.ctx.state.baseUrl}/xs_main.aspx?xh=${sid}&zgh=${sid}`
      const mainDom = await this.ctx.curl(mainUrl, {
        method: 'GET',
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
        },
        timeout: 10000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      const dom$ = cheerio.load(mainDom.data.toString())
      const apiUrl = encodeURI(`${this.ctx.state.baseUrl}/${dom$('a:contains("学生考试查询")').first().attr('href')}`)
      // console.log('apiUrl', apiUrl)

      /* 获取关键查询参数 */
      const keyRes = await this.ctx.curl(apiUrl, {
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
          Referer: `${this.ctx.state.baseUrl}/xs_main.aspx?xh=${sid}`,
        },
        timeout: 5000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      const key$ = cheerio.load(keyRes.data.toString())
      const __EVENTTARGET = key$('#__EVENTTARGET').attr('value')
      const __EVENTARGUMENT = key$('#__EVENTARGUMENT').attr('value')
      const __LASTFOCUS = key$('#__LASTFOCUS').attr('value')
      const __VIEWSTATE = key$('#__VIEWSTATE').attr('value')
      const __VIEWSTATEGENERATOR = key$('#__VIEWSTATEGENERATOR').attr('value')

      /* end */
      const header = ['课程名称', '选课课号', '考试时间', '考试地点', '考试形式', '座位号'] // 列名称
      const res = await this.ctx.curl(apiUrl, {
        method: 'POST',
        headers: {
          Cookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
          Host: this.ctx.state.baseUrl.replace('https://', ''),
          Origin: this.ctx.state.baseUrl,
          Referer: mainUrl,
        },
        data: {
          __EVENTTARGET,
          __EVENTARGUMENT,
          __LASTFOCUS,
          __VIEWSTATE,
          __VIEWSTATEGENERATOR,
          xnd: term ? `${term.split('-')[0]}-${term.split('-')[1]}` : '',
          xqd: term ? term.split('-')[2] : '',
        },
        timeout: 5000,
        rejectUnauthorized: false, // 忽略证书验证
      })
      if (res.status === 200) {
        const tableList = tableToList(res.data.toString(), '#DataGrid1')
        const columnNeed = [1, 0, 3, 4, 5, 6] // 需要提取的列序号

        const info = []
        for (let i = 1; i < tableList.length; i++) {
          const tem = []
          columnNeed.forEach((idx) => (tem.push(tableList[i][idx])))
          info.push(tem)
        }
        return { table: info, header }
      }

      return { table: [], header }
    } catch (err) {
      console.log('err', err)
      throw err
    }
  }
}
